package com.nlscan.ncomgateway.core.model.entity

import android.annotation.SuppressLint
import com.nlscan.ble.NlsBleDevice
import com.nlscan.ble.NlsBleManager
import com.nlscan.ble.util.NBluetoothUtil
import com.nlscan.qdkit.common.core.util.BluetoothUtils

/**
 * <pre>
 * author: lin.qing
 * time  : 2023/3/20
 * desc  : 蓝牙设备实体类
 * </pre>
 */
data class Device(
    val id: Int,
    var address: String,
    var deviceName: String,
    var alias: String?,
    var connectionState: Int,
    var bondState: Int,
    var serialNumber: String,
    var batteryLevel: Int,
) {

    fun getAliasOrDeviceName(): String {
        return if (alias != null && alias!!.isNotEmpty()) {
            alias!!
        } else {
            deviceName
        }
    }

    // TODO: 封装到底层
    fun isConnected(): Boolean {
        return NlsBleManager.CONNECTION_STATE_CONNECTED == connectionState
    }
}

@SuppressLint("MissingPermission")
fun NlsBleDevice.asDevice() = Device(
    id = 0,
    address = address,
    //适配 BluetoothDevice 为空的问题
    //[bugFix] 蓝牙未开启，名称会拿到为空，增加非空处理
    deviceName = originDevice?.name ?: "",
    alias = getAliasName(),
    connectionState = connectionState,
    bondState = if (NBluetoothUtil.checkDeviceHasBond(address)) NlsBleManager.BOND_STATE_BONDED
    else NlsBleManager.BOND_STATE_NONE,
    "",
    -1
)

fun NlsBleDevice.getAliasName(): String {
    return BluetoothUtils.getAliasName(originDevice) ?: ""
}

